﻿#include "uitools.h"
#include <QMessageBox>

bool question(const QString &title, const QString &text, QWidget *parent)
{
    return QMessageBox::question(parent, title, text, QMessageBox::Yes | QMessageBox::No ) == QMessageBox::Yes;
}

void information(const QString &title, const QString &text, QWidget *parent)
{
    QMessageBox::information(parent, title, text);
}

bool confirm(const QString &title, const QString &text, QWidget *parent)
{
    return QMessageBox::question(parent, title, text, QMessageBox::Ok | QMessageBox::Cancel ) == QMessageBox::Ok;
}

QPixmap convertToGray(const QPixmap &pix)
{
    QImage image = pix.toImage();

    int width = image.width();
    int height = image.height();
    bool isGray = true;
    switch (image.format())
    {
    case QImage::Format_Mono:
    case QImage::Format_MonoLSB:
    case QImage::Format_Indexed8:
    {
        QVector<QRgb> table = image.colorTable();
        for (int i = 0; i < table.size(); ++i)
        {
            QRgb& b = table[i];
            if(qAlpha(b)!=0 && !qIsGray(b))
            {
                isGray = false;
                int gray = qGray(b);
                b = qRgba(gray, gray, gray, qAlpha(b));
            }
        }
        image.setColorTable(table);
    }
        break;
    case QImage::Format_RGB32:
    case QImage::Format_ARGB32:
    case QImage::Format_ARGB32_Premultiplied:
#if Q_BYTE_ORDER == Q_LITTLE_ENDIAN
    case QImage::Format_RGBX8888:
    case QImage::Format_RGBA8888:
    case QImage::Format_RGBA8888_Premultiplied:
#endif
        for (int j = 0; j < height; ++j) {
            QRgb *b = (QRgb *)image.scanLine(j);
            for (int i = 0; i < width; ++i) {
                if(qAlpha(b[i])!=0 && !qIsGray(b[i]))
                {
                    isGray = false;
                    int gray = qGray(b[i]);
                    b[i] = qRgba(gray, gray, gray, qAlpha(b[i]));
                }
            }
        }
        break;
    case QImage::Format_RGB16:
        for (int j = 0; j < height; ++j) {
            quint16 *b = (quint16 *)image.scanLine(j);
            for (int i = 0; i < width; ++i) {
                uint c = b[i];
                c = 0xff000000
                        | ((((c) << 3) & 0xf8) | (((c) >> 2) & 0x7))
                        | ((((c) << 5) & 0xfc00) | (((c) >> 1) & 0x300))
                        | ((((c) << 8) & 0xf80000) | (((c) << 3) & 0x70000));
                if(qAlpha(c)!=0 && !qIsGray(c))
                {
                    isGray = false;
                    int gray = qGray(c);
                    c = qRgb(gray, gray, gray);
                    b[i] = (((c) >> 3) & 0x001f)
                            | (((c) >> 5) & 0x07e0)
                            | (((c) >> 8) & 0xf800);
                }
            }
        }
    }
    if(isGray)
        return pix;
    return QPixmap::fromImage(image);
}
